package xgorm

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

type DatabaseConfig struct {
	Host         string
	Port         int
	Dbname       string
	Charset      string
	User         string
	Password     string
	ReadTimeout  int
	WriteTimeout int
	Timeout      int
	Debug        bool
	Loc          string
	// 连接设置
	MaxOpenConn int
	MaxLifeTime time.Duration
	MaxIdleConn int
	MaxIdleTime time.Duration
}

type ConnConfig struct {
	Debug       bool
	MaxOpenConn int
	MaxLifeTime time.Duration
	MaxIdleConn int
	MaxIdleTime time.Duration
}

func (c *DatabaseConfig) dsn() string {
	dsn := "%s:%s@tcp(%s:%d)/%s?timeout=%ds&readTimeout=%ds&writeTimeout=%ds&parseTime=True&loc=%s&charset=%s"
	return fmt.Sprintf(dsn, c.User, c.Password, c.Host, c.Port, c.Dbname, c.Timeout, c.ReadTimeout, c.WriteTimeout, c.Loc, c.Charset)
}

func NewMysqlDB(cfg *DatabaseConfig) (*gorm.DB, error) {
	db, err := gorm.Open(mysql.Open(cfg.dsn()), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	if cfg.Debug {
		db = db.Debug()
	}
	client, err := db.DB()
	if err != nil {
		return nil, err
	}

	client.SetMaxOpenConns(cfg.MaxOpenConn)
	client.SetMaxIdleConns(cfg.MaxIdleConn)
	client.SetConnMaxIdleTime(cfg.MaxIdleTime)
	client.SetConnMaxLifetime(cfg.MaxLifeTime)
	return db, nil
}

func NewMysqlDBByDsn(dsn string, cfg *ConnConfig, l logger.Interface) (*gorm.DB, error) {
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: l,
	})
	if err != nil {
		return nil, err
	}
	if cfg.Debug {
		db = db.Debug()
	}
	client, err := db.DB()
	if err != nil {
		return nil, err
	}

	client.SetMaxOpenConns(cfg.MaxOpenConn)
	client.SetMaxIdleConns(cfg.MaxIdleConn)
	client.SetConnMaxIdleTime(cfg.MaxIdleTime)
	client.SetConnMaxLifetime(cfg.MaxLifeTime)
	return db, nil
}
